# -*- coding: utf-8 -*-

from scpy2.conveyor_driven_worker import ConveyorDrivenWorker
import datetime
import json
from parse_util.trans_recruitment_format import job_info_trans

class ResumeStorer(ConveyorDrivenWorker):

    def _process_task_msg(self, msg, params=None):
        self.logger.debug(type(msg))
        for x in msg:
            # self.logger.debug(type(x))
            # self.logger.debug(type(x[0]))
            y = x

            self.__save_to_pqsql(y)
            # self.__save_to_dynamodb(y)

    def _check_info_exist(self, _url, _company_name, sqle):
        sqle.sql = 'select * from resume where url=%s and company_name=%s'
        sqle.empty_params()
        sqle.params.append(_url)
        sqle.params.append(_company_name)
        result = sqle.execute_dataset()
        if len(result):
            return True
        else:
            return False

    def __save_to_pqsql(self, info):
        sqle = self._components['sqlexecutor']
        try:
            _schoolList = list()
            _majorList = list()
            _url = info.get('url', '')
            _companyName = info.get('companyName', '')
            for item in info.get('educationInfo', []):
                if item.get('school'):
                    _schoolList.append(item.get('school'))
                if item.get('major'):
                    _majorList.append(item.get('major'))
            _values = [
                info.get('companyName', ''),
                info.get('url', ''),
                info.get('beginDate', ''),
                info.get('endDate', ''),
                info.get('releaseDate', ''),
                info.get('personalInfo').get('sex', ''),
                info.get('personalInfo').get('degree', ''),
                float(info.get('personalInfo').get('workingExperienceYear', 0)),
                info.get('personalInfo').get('dob', ''),
                info.get('personalInfo').get('location', ''),
                info.get('jobTitle', ''),
                info.get('industry', ''),
                info.get('detail', ''),
                info.get('preCompanyName') if info.get('preCompanyName') else '',
                info.get('nextCompanyName') if info.get('nextCompanyName') else '',
                _schoolList,
                _majorList,
                json.dumps(info.get('jobsExpectInfo', '')),
                json.dumps(info.get('educationInfo', '')),
            ]
            if not self._check_info_exist(_url, _companyName, sqle):
                sqle.sql = """
                          INSERT INTO resume(
                                  company_name,
                                  url,
                                  begin_time,
                                  end_time,
                                  release_time,
                                  sex,
                                  degree,
                                  working_years,
                                  dob,
                                  location,
                                  job_title,
                                  industry,
                                  detail,
                                  pre_company,
                                  next_company,
                                  school,
                                  major,
                                  expect_detail,
                                  education_detail
                          )  VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
                          """
                sqle.empty_params()
                sqle.params = _values
                sqle.execute_non_query()
            else:
                self.logger.warn('resume info already exist')
        except Exception,e:
            self._logger.error('insert resume info failed for %s'%str(e))







    # def __save_to_dynamodb(self, x):
    #     table = self._components['dynamodb'].get_table(self._cfg['dynamodb_table'])
    #     table.put_item(Item={
    #         'url': x['url'],
    #         'content': x['content'][0],
    #         'label_content': x['content'][1]
    #     })


if __name__ == '__main__':
    worker = ResumeStorer()
    worker.run()
